package vn.co.thn.web.hotvideo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vn.co.thn.web.hotvideo.common.BeanBase;
import vn.co.thn.web.hotvideo.common.ControllerBase;
import vn.co.thn.web.hotvideo.data.jpa.Category;
import vn.co.thn.web.hotvideo.model.CategoryModel;

@SuppressWarnings("serial")
public class AdminCategory extends ControllerBase {
	private CategoryModel categoryModel = new CategoryModel();
	@Override
	protected void Get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String query = request.getQueryString();
		if (query != null && query.trim().length() > 0) {
			if (request.getParameter("action") != null) {
				if (request.getParameter("action").equalsIgnoreCase("new")) {
					request.setAttribute("action", 1);
					Forward("admin_category");
					return;
				}
				if (request.getParameter("action").equalsIgnoreCase("edit")) {
					Category category=categoryModel.getObject(Long.parseLong(request.getParameter("key")));
					request.setAttribute("data", category);
					request.setAttribute("action", 2);
					Forward("admin_category");
					return;
				}
				if (request.getParameter("action").equalsIgnoreCase("delete")) {
					categoryModel.Delete(Long.parseLong(request.getParameter("key")));
					response.setContentType("text/html;charset=UTF-8");
					PrintWriter out = response.getWriter();
					List<Category>lst=categoryModel.getList();
					if (lst.size() > 0) {
						out.println("<table border=\"1\">");
						for (Category obj : lst) {
							out.println("<tr>");
							out.println("<td>" + obj.getKey() + "</td>");
							out.println("<td>" + obj.getName() + "</td>");
							out.println("<td><a href=\"JavaScript:ajax('?action=delete&key=" + obj.getKey() + "','htmldata')\" >Delete</a></td>");
							out.println("<td><a href=\"?action=edit&key=" + obj.getKey() + "\">Edit</a></td>");
							out.println("</tr>");
						}

						out.println("</table>");
					}else{
						out.println("");
					}
					return;
				}
			}
		} else {
			
			request.setAttribute("datalist", categoryModel.getList());
			request.setAttribute("action", 0);
			Forward("admin_category");
		}

	}

	@Override
	protected void Post(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Category category=BeanBase.RequestToObject(request, Category.class);
		categoryModel.Update(category);
		Redirect("/admin/category");
	}

}
